<template>
  <page-header-wrapper :title="false">
    <a-card title="押金管理">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.queryCondition" allow-clear placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleCreate()">新增押金</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data-source="loadData"
        :scroll="{ x: `${columns.length}0%` }"
        :footer="loadData.length === 11 ? handleFooterShow : null"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="depClsType" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" v-if="record?.depClsType == 1">经销商</a-tag>
            <a-tag color="#D15B47" v-if="record?.depClsType == 2">供应商</a-tag>
            <a-tag color="#82AF6F" v-if="record?.depClsType == 3">运营商</a-tag>
          </template>
        </span>
        <span slot="depType" slot-scope="text, record">
          <template>
            <a-tag color="#82AF6F" v-if="record?.depType == 1">收取</a-tag>
            <a-tag color="#D15B47" v-if="record?.depType == 0">缴纳</a-tag>
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已退还</a-tag>
            <a-tag color="#D15B47" v-if="record?.status == 0">待归还</a-tag>
          </template>
        </span>
        <span slot="checkStatus" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.checkStatus == 1">已审核</a-tag>
            <a-tag color="#D15B47" v-if="record?.checkStatus == 0">待审核</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="record.createTime !== '合计'">
            <a-tag color="#428bca" @click="handleDetail(record)">进入</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
  </page-header-wrapper>
</template>

<script>
import { getDepositListUsingGET, addEmployeesUsingPOST1 ,exportDepositListUsingPOST } from '@/api/api/qiantaizhangwu.ts'
import CreateForm from './CreateForm'
export default {
  name: 'CashierDepositIndex',
  components: {
    CreateForm,
  },
  data() {
    return {
      mdl: null,
      priceMdl: null,
      visible: false,
      priceVisible: false,
      value: '',
      confirmLoading: false,
      priceLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      pagination: {
        total: 0,
      },

      loading: false,
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      // 表头
      footerDataSource:[],
      columns: [
        {
          title: '创建日期',
          width:144,
          dataIndex: 'createTime',
        },
        {
          title: '创建人',
          width:120,
          dataIndex: 'creatorName',
        },
        {
          title: '描述',
          width:120,
          dataIndex: 'memo',
        },
        {
          title: '押金类型',
          width:120,
          dataIndex: 'depType',
          scopedSlots: { customRender: 'depType' },
        },
        {
          title: '账户',
          width:120,
          dataIndex: 'accountName',
        },
        {
          title: '金额',
          width:120,
          dataIndex: 'amount',
        },
        {
          title: '押金归属',
          width:120,
          dataIndex: 'depClsType',
          scopedSlots: { customRender: 'depClsType' },
        },
        {
          title: '状态',
          width:120,
          dataIndex: 'status',
          needTotal: true,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '审核状态',
          width:120,
          dataIndex: 'checkStatus',
          scopedSlots: { customRender: 'checkStatus' },
        },
        {
          title: '归属店',
          width:120,
          dataIndex: 'storeName',
        },
        {
          title: '退还日期',
          width:120,
          dataIndex: 'retTime',
        },
        {
          title: '退还人',
          width:120,
          dataIndex: 'retName',
        },
        {
          title: '退还账户',
          width:120,
          dataIndex: 'retAccountName',
        },
        {
          title: '操作',
          fixed:'right',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      optionAlertShow: false,
    }
  },
  mounted() {
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportDepositListUsingPOST({...params}).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '押金管理列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    }, 
    handleFooterShow(){
      if(this.footerDataSource.length > 0){
      return (
         <a-table
          ref="table"
          size="default"
          rowKey={Math.random}
          pagination={false}
          columns={this.columns}
          dataSource={this.footerDataSource}
          showHeader={false}
          class="j-table-force-nowrap"
        ></a-table>
      )}
    }, 
    handleSearch(params) {
      this.loading = true
      getDepositListUsingGET(params)
        .then((res) => {
          this.loadData = res.data.list.map((item)=>{return {...item,createTime:item.createTime ?? '合计'}})
          this.footerDataSource = [{...res.data.list[res.data.list.length - 1],createTime:'合计'}]
          this.loading = false
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    handleCreate(record) {
      // this.mdl = { ...record }
      this.visible = true
    },
    handleDetail(record) {
      this.$router.push({ path: `/cashier/deposit/${record.id}` })
    },
    handleOk() {
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.id > 0) {
          } else {
            addEmployeesUsingPOST1({ ...values })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.visible = false
                this.confirmLoading = false
                this.$message.success('添加成功')
              })
              .catch(() => {
                this.confirmLoading = false
                this.$message.error('添加失败,请联系管理员!')
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },

    toggleAdvanced() {
      this.advanced = !this.advanced
    },
  },
}
</script>
